import java.util.HashMap;
import java.util.Map;

public class CopyRandomList {
    // leetcode 随机链表的复制
    // https://leetcode.cn/problems/copy-list-with-random-pointer/description/?envType=study-plan-v2&envId=top-100-liked
    public Node copyRandomList(Node head) {
        Map<Node,Node> map = new HashMap<>();
        Node cur = head;
        // 通过哈希表来记录深拷贝出来的新节点和被拷贝的节点
        while (cur != null) {
            Node newNode = new Node(cur.val);
            map.put(cur,newNode);
            cur = cur.next;
        }
        for (Map.Entry<Node,Node> entry : map.entrySet()) {
            Node old = entry.getKey(), fresh = entry.getValue();
            fresh.next = map.get(old.next);
            fresh.random = map.get(old.random);
        }
        return map.get(head);
    }
}
